package impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.UsersDao;
import entity.Books;
import entity.Users;

public class UsersDaoImpl extends BaseDao  implements UsersDao {

	@Override
	public Users LoginUser(Users u) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String sql="SELECT * FROM users";
		List<Users> users=new ArrayList<Users>();
		try {
			conn=getConnection();
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next()){
				Users user=new Users();
				user.setId(rs.getString("id"));
				user.setUser_name(rs.getString("user_name"));
				user.setUser_pwd(rs.getString("user_pwd")); 
				user.setUser_role(rs.getString("user_role"));
				users.add(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeAll(rs, pstmt, conn);
		}
		int is=0;
		for(int i=0;i<users.size();i++){
			if(users.get(i).getUser_name().equals(u.getUser_name())&&users.get(i).getUser_pwd().equals(u.getUser_pwd())){
				u=users.get(i);
				is=1;
				break;
			}
		}


		if(is==0){
			u=null;
			System.out.println("验证失败");
		}else{
			System.out.println("验证正确");
		}
		return u;
	}

	@Override
	public int addUser(Users users) {	 
		String sql = "INSERT users (id,user_name,user_pwd,user_role) VALUES(?,?,?,?)";
		Object[] objects = {users.getId(),users.getUser_name(),users.getUser_pwd(),users.getUser_role()};
		return execeteUpdata(sql, objects);
	}
} 
